﻿using System;
using Newtonsoft.Json.Linq;
using TrinityAPI.Base;
using TrinityAPI.Base.Tools;
using TrinityAPI.Base.Models;
using Jd.Api.Request;
using Jd.Api;

namespace JingDong.Open.Platform
{
    public class GetOrderReceiverinfo : IAction
    {
        public JToken Invoke(JObject dataset, params JToken[] args)
        {
            try
            {
                var request = args.Length > 0 ? args[0] as JObject : dataset.GetJsonObject("request");
                var dbOrderInfo = dataset.GetJsonObjectValue("orderinfo");
                var constant = dataset.GetJsonObject("constant");
                var jingdongAPIConfig = constant.GetJsonObject("jingdongAPIConfig");
                var eShopCodes = constant.GetJsonObject("eShopCodes");

                string deliveryOrderCode = request.GetJsonObjectStringValue("deliveryOrderCode");
                string ownerCode = request.GetJsonObjectStringValue("ownerCode");
                string url = jingdongAPIConfig.GetJsonObjectStringValue("url");
                string appKey = jingdongAPIConfig.GetJsonObjectStringValue("app_key");
                string appSecret = jingdongAPIConfig.GetJsonObjectStringValue("app_secret");

                if (string.IsNullOrWhiteSpace(url) || string.IsNullOrWhiteSpace(appKey) || string.IsNullOrWhiteSpace(appSecret))
                    throw new BaseException("@0002", "");

                if (string.IsNullOrWhiteSpace(ownerCode))
                    throw new BaseException("@4002", "");

                string eShopCode = eShopCodes.GetJsonObjectStringValue(ownerCode);
                if (string.IsNullOrWhiteSpace(eShopCode))
                    throw new BaseException("@4002", "");

                if (string.IsNullOrWhiteSpace(deliveryOrderCode))
                    throw new BaseException("@4003", "");

                string orderId = deliveryOrderCode;

                string accessToken = GetAccessToken.GetToken(eShopCode, constant);

                var client = new DefaultJdClient(url, appKey, appSecret);

                JObject orderInfo = null;
                if (dbOrderInfo != null && dbOrderInfo.Type == JTokenType.Array && dbOrderInfo.HasValues && dbOrderInfo[0] is JObject)
                {
                    orderInfo = JSONHelper.JsonToJObject((dbOrderInfo[0] as JObject).GetJsonObjectStringValue("responseJson"));
                }

                if (orderInfo == null)
                {
                    PopOrderGetRequest orderRequest = new PopOrderGetRequest();
                    orderRequest.orderId = orderId;
                    orderRequest.optionalFields = "orderId,venderId,orderType,consigneeInfo";
                    var orderResponse = client.Execute(orderRequest, accessToken, DateTime.Now.ToLocalTime());

                    if (!orderResponse.IsError)
                    {
                        var orderData = JSONHelper.JsonToJObject(orderResponse.Body);
                        orderInfo = orderData.GetJsonObject("jingdong_pop_order_get_responce").GetJsonObject("orderDetailInfo").GetJsonObject("orderInfo");
                    }
                }

                if (orderInfo == null)
                    throw new BaseException("@4004", "");

                var consigneeInfo = orderInfo.GetJsonObject("consigneeInfo");
                if (consigneeInfo == null)
                    throw new BaseException("@4005", "");

                string fullname = null;
                string fullAddress = null;
                string province = consigneeInfo.GetJsonObjectStringValue("province");
                string city = consigneeInfo.GetJsonObjectStringValue("city");
                string county = consigneeInfo.GetJsonObjectStringValue("county");
                string town = consigneeInfo.GetJsonObjectStringValue("town");
                var tdeclient = Jd.ACES.TDEClient.GetInstance(url, appKey, appSecret, accessToken);
                try
                {
                    fullname = tdeclient.DecryptString(consigneeInfo.GetJsonObjectStringValue("fullname"));
                }
                catch (Exception ex)
                {
                    throw new BaseException("@4006", "");
                }
                try
                {
                    fullAddress = tdeclient.DecryptString(consigneeInfo.GetJsonObjectStringValue("fullAddress"));
                }
                catch (Exception ex)
                {
                    throw new BaseException("@4007", "");
                }

                string desen_telephone = consigneeInfo.GetJsonObjectStringValue("desen_telephone");
                string desen_mobile = consigneeInfo.GetJsonObjectStringValue("desen_mobile");

                var response = new JObject();
                response["countryCode"] = "CN";
                response["province"] = province;
                response["city"] = city;
                response["district"] = county;
                response["town"] = town;
                response["detailAddress"] = fullAddress;
                response["name"] = fullname;
                response["mobile"] = desen_mobile;
                response["tel"] = desen_telephone;
                return new JArray() { response };
            }
            catch(BaseException ex)
            {
                if (!string.IsNullOrEmpty(ex.Message))
                    throw ex;
                throw new Exception(ex.Code);
            }
            catch (Exception ex)
            {
                LogHelper.Info("GetOrderReceiverinfo fail: " + ex.Message);
                throw new Exception("@4001");
            }
        }
    }
}
